package com.lebang.service;
import com.alibaba.fastjson.JSON;
import com.lebang.component.RedisClient;
import com.lebang.domain.AppAdContro;
import com.lebang.domain.AppAdControAppStore;
import com.lebang.domain.AppAdControHistory;
import com.lebang.example.AppAdControExample;
import com.lebang.mapper.AppAdControAppStoreMapper;
import com.lebang.mapper.AppAdControHistoryMapper;
import com.lebang.mapper.AppAdControMapper;
import com.lebang.model.Whether;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;

/**
 * 数据源排序
 *
 * @Author hwq
 * @Date 2020-03-16
 */
@Service
public class AppAdControService extends BaseService<AppAdContro, Integer, AppAdControExample> {
    @Autowired
    private AppAdControMapper appAdControMapper;
    @Autowired
    private RedisCacheService redisCacheService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private AppAdControAppStoreMapper detailMapper;
    @Autowired
    private AppAdControHistoryMapper appAdControHistoryMapper;
    private static final String KEY = "AppAdContro:";
    public static final String APP_AD_COUNT_KEY = "AppAdControCount";

    public AppAdContro initByKey(AppAdContro vo) {
        if (vo.getEnable().equals(Whether.NO.getDbIndex())) {
            redisCacheService.delCache(KEY + vo.getAdKey());
        } else {
            redisCacheService.addCacheByKey(KEY + vo.getAdKey(), JSON.toJSONString(vo));
        }
        return vo;

    }

    public Optional<String> selectAdIdByKey(String key, int count, String appStore) {
        //渠道有就用渠道的
        AppAdControAppStore appAdControAppStore = detailMapper.selectByAdKeyAndAppStore(key, appStore);
        if (appAdControAppStore != null) {
            if (count >= appAdControAppStore.getCount()) {
                return Optional.ofNullable(appAdControAppStore.getSdkLastKey());
            } else {
                return Optional.ofNullable(appAdControAppStore.getSdkFirstKey());
            }
        }
        //否则走通用的
        AppAdContro vo = redisCacheService.selectByKey(KEY + key, AppAdContro.class);
        if (vo == null) {
            vo = appAdControMapper.selectByAdKey(key);
            if (vo == null) {
                return Optional.empty();
            }
            vo = this.initByKey(vo);
        }
        if (count >= vo.getCount()) {
            return Optional.ofNullable(vo.getSdkLastKey());
        } else {
            return Optional.ofNullable(vo.getSdkFirstKey());
        }
    }

    /**
     * 返回这个数据源通用今日的播放量
     *
     * @param key
     * @return
     */
    public int getCountByKey(String key) {
        String now = LocalDate.now().format(DateTimeFormatter.ISO_DATE) + ":";
        Optional<String> str = redisClient.Optionalhget(now + APP_AD_COUNT_KEY, key);
        return str.map(Integer::parseInt).orElse(0);
    }

    /**
     * 返回这个数据源通用今日的播放量
     *
     * @param key
     * @return
     */
    public int getCountByKey(String key, String appStore) {
        String now = LocalDate.now().format(DateTimeFormatter.ISO_DATE) + ":";
        Optional<String> str = redisClient.Optionalhget(now + APP_AD_COUNT_KEY, key+":"+appStore);
        return str.map(Integer::parseInt).orElse(0);
    }

    /**
     * 返回这个数据源昨日的播放量
     *
     * @param key
     * @return
     */
    public int getCountByKeyYesterday(String key) {
        String now = LocalDate.now().minusDays(1).format(DateTimeFormatter.ISO_DATE) + ":";
        Optional<String> str = redisClient.Optionalhget(now + APP_AD_COUNT_KEY, key);
        return str.map(Integer::parseInt).orElse(0);
    }

    /**
     * 返回这个数据源昨日的播放量
     *
     * @param key
     * @return
     */
    public int getCountByKeyYesterday(String key, String appStore) {
        String now = LocalDate.now().minusDays(1).format(DateTimeFormatter.ISO_DATE) + ":" ;
        Optional<String> str = redisClient.Optionalhget(now + APP_AD_COUNT_KEY, key+":"+appStore);
        return str.map(Integer::parseInt).orElse(0);
    }

    public static final String SDK_HASH = "SDK_HASH";

    /**
     * 播放量+1
     *
     * @param key
     */
    public void addCountByKey(String key, String sdkKey, String appStore,String memberId) {
        String now = LocalDate.now().format(DateTimeFormatter.ISO_DATE) + ":";
        if (detailMapper.chekByAdKeyAndAppStore(key, appStore) > 0) {
            redisClient.hincrby(now + APP_AD_COUNT_KEY, key+":"+appStore, 1L);
            //过期时间修改注释
            //redisClient.expire(now + COUNT_KEY, 86000);
        }else {
            redisClient.hincrby(now + APP_AD_COUNT_KEY, key, 1L);
            //过期时间修改注释
            //redisClient.expire(now + COUNT_KEY, 86000);
        }
        redisClient.hincrby(now + SDK_HASH, sdkKey, 1L);
        //过期时间修改注释
        //redisClient.expire(now + SDK_HASH, 86000);
        redisClient.hset(now + APP_AD_COUNT_KEY+key,memberId,"1");
        //过期时间修改注释
        //redisClient.expire(now + COUNT_KEY+key,86000);
    }

    /**
     * 返回这个数据源今日的播放量
     *
     * @param sdkKey
     * @return
     */
    public int getCountBySdkKey(String sdkKey) {
        String now = LocalDate.now().format(DateTimeFormatter.ISO_DATE) + ":";
        Optional<String> str = redisClient.Optionalhget(now + SDK_HASH, sdkKey);
        return str.map(Integer::parseInt).orElse(0);
    }

    /**
     * 返回这个数据源昨日的播放量
     *
     * @param sdkKey
     * @return
     */
    public int getCountBySdkKeyYesterday(String sdkKey) {
        String now = LocalDate.now().minusDays(1).format(DateTimeFormatter.ISO_DATE) + ":";
        Optional<String> str = redisClient.Optionalhget(now + SDK_HASH, sdkKey);
        return str.map(Integer::parseInt).orElse(0);
    }

    public boolean checkAppStore(String key, String appStore) {
        return detailMapper.chekByAdKeyAndAppStore(key, appStore) > 0;
    }


    public void addData ( LocalDateTime dateTime){
        LocalDate DateNow=dateTime.toLocalDate();
        List<AppAdControHistory> strings=appAdControMapper.selectAllAdKey();
        strings.forEach(s->{
            s.setCreateTime(LocalDateTime.now());
            s.setModifyTime(LocalDateTime.now());
            s.setTodayCount(this.getCountByKey(s.getAdKey()));
            s.setTodayMember((int) this.getMemberCountByKeyToDay(s.getAdKey()));
            s.setTime(DateNow);
            appAdControHistoryMapper.insertSelective(s);
        });
    }


    /**
     * 返回这个数据源通用今日的播放用户数
     *
     * @param key
     * @return
     */
    public long getMemberCountByKeyToDay(String key) {
        String now = LocalDate.now().format(DateTimeFormatter.ISO_DATE) + ":";
        Optional<Long> str = Optional.ofNullable(redisClient.hlen(now + APP_AD_COUNT_KEY+key));
        return str.orElse(0L);
    }

}
